package cn.rubintry.bug.ui.components

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.rubintry.bug.ui.components.pojo.AppUpdateMsgModel
import com.blankj.utilcode.util.SizeUtils
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import java.lang.ref.WeakReference

class AppUpdateDialog(
    val builder: Builder,
    context: Context,
    cancelable: Boolean,
    cancelListener: DialogInterface.OnCancelListener?
) : AlertDialog(context, cancelable, cancelListener) {

    private var isComplete = false

    private var tvTitle : TextView ?= null
    private var tvUpgrade : TextView ?= null
    private var tvFileSize : TextView ?= null
    private var rvUpdateMsg : RecyclerView ?= null
    private var mAdapter : UpdateMsgAdapter?= null

    @SuppressLint("MissingInflatedId", "SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_update)
        tvTitle = findViewById(R.id.tvTitle)
        tvFileSize = findViewById(R.id.tvFileSize)
        rvUpdateMsg = findViewById(R.id.rvUpdateMsg)
        tvUpgrade = findViewById(R.id.tvUpgrade)
        rvUpdateMsg?.layoutManager = LinearLayoutManager(context)
        rvUpdateMsg?.isNestedScrollingEnabled = false
        mAdapter = UpdateMsgAdapter(mutableListOf())
        rvUpdateMsg?.adapter = mAdapter
        mAdapter?.submitList(builder.getMsgList())
        tvTitle?.text = builder.getTitle()
        tvUpgrade?.setOnClickListener {
            if(isComplete){
                dismiss()
                return@setOnClickListener
            }
            builder.getOnClickListener()?.invoke(this)
        }
        if(builder.getFileSize() != null){
            tvFileSize?.text = "${builder.getFileSize()!! / 1024 / 1024} MB"
            tvFileSize?.visibility = View.VISIBLE
        }else{
            tvFileSize?.visibility = View.GONE
        }
    }


    fun updateProgress(progress: Int){
        tvUpgrade?.text = "${progress} %"
    }


    fun complete() {
        isComplete = true
        tvUpgrade?.text = "完成"
    }

    override fun show() {
        super.show()
        window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        // 然后弹出输入法
        // 然后弹出输入法
        window?.decorView?.setPadding(0, 0, 0, 0)
        window?.setGravity(Gravity.CENTER)
        //调整窗体大小
        //调整窗体大小
        val params = window?.attributes
        params?.width = SizeUtils.dp2px(270f)
        params?.height = ViewGroup.LayoutParams.WRAP_CONTENT
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window?.setAttributes(params)
    }



    class Builder(context: Context){
        private var onClickListener: ((dialog: AppUpdateDialog) -> Unit?)? = null
        private var msgList: List<AppUpdateMsgModel> = arrayListOf()
        private var fileSize: Long ?= null
        private var title: String = ""
        private var contextWeakReference: WeakReference<Context> ?= null


        init {
            contextWeakReference = WeakReference(context)
        }


        /**
         * 设置标题(如：发现新版本)
         */
        fun setTitle(title: String): Builder {
            this.title = title
            return this
        }


        /**
         * 设置文件大小
         */
        fun setFileSize(size: Long): Builder {
            this.fileSize = size
            return this
        }

        fun setMsgList(msgList: List<AppUpdateMsgModel>): Builder {
            this.msgList = msgList
            return this
        }

        fun setOnUpgradeClick(onClickListener: (dialog: AppUpdateDialog) -> Unit) : Builder {
            this.onClickListener = onClickListener
            return this
        }

        fun getOnClickListener(): ((dialog: AppUpdateDialog) -> Unit?)? {
            return onClickListener
        }

        fun create(): AppUpdateDialog {
            if(contextWeakReference == null){
                throw IllegalArgumentException("请传入正确的context!!!")
            }
            return AppUpdateDialog(this , contextWeakReference?.get()!! , true , {})
        }

        fun getTitle(): String {
            return title
        }

        fun getMsgList(): List<AppUpdateMsgModel> {
            return msgList
        }

        fun getFileSize(): Long? {
            return fileSize
        }

    }

    inner class UpdateMsgAdapter(private val msgList: List<AppUpdateMsgModel>) : BaseQuickAdapter<AppUpdateMsgModel , QuickViewHolder>(msgList){
        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(
            holder: QuickViewHolder,
            position: Int,
            item: AppUpdateMsgModel?
        ) {
            holder.getView<TextView>(R.id.tvMsg).text = "${position + 1}.${item?.message}"
        }

        override fun onCreateViewHolder(
            context: Context,
            parent: ViewGroup,
            viewType: Int
        ): QuickViewHolder {
            return QuickViewHolder(R.layout.item_update_msg , parent)
        }
    }
}